import React, { useState } from 'react';
import { 
  Typography, 
  Table, 
  Card, 
  Space, 
  Button, 
  Tag, 
  Input, 
  Select, 
  Popconfirm,
  Modal,
  Descriptions,
  Alert,
  Progress
} from 'antd';
import {
  SafetyCertificateOutlined,
  SearchOutlined,
  DownloadOutlined,
  SyncOutlined,
  DeleteOutlined,
  EyeOutlined,
  CloudUploadOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Option } = Select;

interface Certificate {
  id: string;
  domain: string;
  provider: string;
  status: 'valid' | 'expired' | 'expiring' | 'pending' | 'failed';
  issueDate: string;
  expiryDate: string;
  autoRenew: boolean;
  deployStatus: 'deployed' | 'not_deployed' | 'deploying';
}

const CertificateManage: React.FC = () => {
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedCertificate, setSelectedCertificate] = useState<Certificate | null>(null);

  // 模拟证书数据
  const [certificates] = useState<Certificate[]>([
    {
      id: '1',
      domain: 'example.com',
      provider: "Let's Encrypt",
      status: 'valid',
      issueDate: '2024-01-15',
      expiryDate: '2024-04-15',
      autoRenew: true,
      deployStatus: 'deployed'
    },
    {
      id: '2',
      domain: '*.demo.com',
      provider: 'ZeroSSL',
      status: 'expiring',
      issueDate: '2023-12-01',
      expiryDate: '2024-02-01',
      autoRenew: false,
      deployStatus: 'not_deployed'
    },
    {
      id: '3',
      domain: 'test.com',
      provider: '阿里云SSL',
      status: 'expired',
      issueDate: '2023-10-01',
      expiryDate: '2024-01-01',
      autoRenew: false,
      deployStatus: 'not_deployed'
    },
    {
      id: '4',
      domain: 'api.example.com',
      provider: "Let's Encrypt",
      status: 'pending',
      issueDate: '',
      expiryDate: '',
      autoRenew: true,
      deployStatus: 'deploying'
    }
  ]);

  const getStatusConfig = (status: Certificate['status']) => {
    const configs = {
      valid: { color: 'success', text: '有效' },
      expired: { color: 'error', text: '已过期' },
      expiring: { color: 'warning', text: '即将过期' },
      pending: { color: 'processing', text: '申请中' },
      failed: { color: 'error', text: '申请失败' }
    };
    return configs[status];
  };

  const getDeployStatusConfig = (status: Certificate['deployStatus']) => {
    const configs = {
      deployed: { color: 'success', text: '已部署' },
      not_deployed: { color: 'default', text: '未部署' },
      deploying: { color: 'processing', text: '部署中' }
    };
    return configs[status];
  };

  const getDaysUntilExpiry = (expiryDate: string) => {
    if (!expiryDate) return null;
    const today = new Date();
    const expiry = new Date(expiryDate);
    const diffTime = expiry.getTime() - today.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  const filteredCertificates = certificates.filter(cert => {
    const matchesSearch = cert.domain.toLowerCase().includes(searchText.toLowerCase()) ||
                         cert.provider.toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = statusFilter === 'all' || cert.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const handleViewDetail = (certificate: Certificate) => {
    setSelectedCertificate(certificate);
    setDetailModalVisible(true);
  };

  const handleRenew = (certificate: Certificate) => {
    console.log('续期证书:', certificate.domain);
    // 实现续期逻辑
  };

  const handleDeploy = (certificate: Certificate) => {
    console.log('部署证书:', certificate.domain);
    // 实现部署逻辑
  };

  const handleDelete = (certificate: Certificate) => {
    console.log('删除证书:', certificate.domain);
    // 实现删除逻辑
  };

  const handleDownload = (certificate: Certificate) => {
    console.log('下载证书:', certificate.domain);
    // 实现下载逻辑
  };

  const columns: ColumnsType<Certificate> = [
    {
      title: '域名',
      dataIndex: 'domain',
      key: 'domain',
      render: (text: string) => (
        <Space>
          <SafetyCertificateOutlined style={{ color: '#1890ff' }} />
          <Text strong>{text}</Text>
        </Space>
      ),
    },
    {
      title: 'CA机构',
      dataIndex: 'provider',
      key: 'provider',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: Certificate['status'], record) => {
        const config = getStatusConfig(status);
        const daysUntilExpiry = getDaysUntilExpiry(record.expiryDate);
        
        return (
          <Space direction="vertical" size="small">
            <Tag color={config.color}>{config.text}</Tag>
            {daysUntilExpiry !== null && (
              <Text type={daysUntilExpiry < 30 ? 'danger' : 'secondary'} style={{ fontSize: 12 }}>
                {daysUntilExpiry > 0 ? `${daysUntilExpiry}天后过期` : `已过期${Math.abs(daysUntilExpiry)}天`}
              </Text>
            )}
          </Space>
        );
      },
    },
    {
      title: '部署状态',
      dataIndex: 'deployStatus',
      key: 'deployStatus',
      render: (status: Certificate['deployStatus']) => {
        const config = getDeployStatusConfig(status);
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '自动续期',
      dataIndex: 'autoRenew',
      key: 'autoRenew',
      render: (autoRenew: boolean) => (
        <Tag color={autoRenew ? 'blue' : 'default'}>
          {autoRenew ? '已启用' : '已禁用'}
        </Tag>
      ),
    },
    {
      title: '过期时间',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      render: (date: string) => date || '-',
      sorter: (a, b) => new Date(a.expiryDate || 0).getTime() - new Date(b.expiryDate || 0).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      width: 280,
      render: (_, record) => (
        <Space size="small" wrap>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          
          {record.status === 'valid' && (
            <Button
              type="link"
              size="small"
              icon={<SyncOutlined />}
              onClick={() => handleRenew(record)}
            >
              续期
            </Button>
          )}
          
          {record.deployStatus === 'not_deployed' && record.status === 'valid' && (
            <Button
              type="link"
              size="small"
              icon={<CloudUploadOutlined />}
              onClick={() => handleDeploy(record)}
            >
              部署
            </Button>
          )}
          
          <Button
            type="link"
            size="small"
            icon={<DownloadOutlined />}
            onClick={() => handleDownload(record)}
            disabled={record.status !== 'valid'}
          >
            下载
          </Button>
          
          <Popconfirm
            title="确定要删除这个证书吗？"
            description="删除后无法恢复，请谨慎操作。"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
            icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  // 统计信息
  const stats = {
    total: certificates.length,
    valid: certificates.filter(c => c.status === 'valid').length,
    expiring: certificates.filter(c => c.status === 'expiring').length,
    expired: certificates.filter(c => c.status === 'expired').length,
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '24px' }}>
        <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
          <SafetyCertificateOutlined style={{ marginRight: '8px', color: '#52c41a' }} />
          证书管理
        </Title>
        <Text type="secondary">
          查看和管理所有SSL证书，包括续期、部署和下载
        </Text>
      </div>

      {/* 统计卡片 */}
      <div style={{ 
        display: 'grid', 
        gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', 
        gap: '16px', 
        marginBottom: '24px' 
      }}>
        <Card size="small">
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>{stats.total}</div>
            <div style={{ color: '#666' }}>总证书数</div>
          </div>
        </Card>
        <Card size="small">
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>{stats.valid}</div>
            <div style={{ color: '#666' }}>有效证书</div>
          </div>
        </Card>
        <Card size="small">
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#fa8c16' }}>{stats.expiring}</div>
            <div style={{ color: '#666' }}>即将过期</div>
          </div>
        </Card>
        <Card size="small">
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#ff4d4f' }}>{stats.expired}</div>
            <div style={{ color: '#666' }}>已过期</div>
          </div>
        </Card>
      </div>

      {/* 搜索和筛选 */}
      <Card style={{ marginBottom: '16px' }}>
        <Space style={{ marginBottom: '16px' }}>
          <Input
            placeholder="搜索域名或CA机构"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 300 }}
          />
          <Select
            placeholder="选择状态"
            value={statusFilter}
            onChange={setStatusFilter}
            style={{ width: 150 }}
          >
            <Option value="all">全部状态</Option>
            <Option value="valid">有效</Option>
            <Option value="expiring">即将过期</Option>
            <Option value="expired">已过期</Option>
            <Option value="pending">申请中</Option>
          </Select>
        </Space>

        {selectedRowKeys.length > 0 && (
          <Alert
            message={`已选择 ${selectedRowKeys.length} 个证书`}
            action={
              <Space>
                <Button size="small">批量续期</Button>
                <Button size="small">批量部署</Button>
                <Button size="small" danger>批量删除</Button>
              </Space>
            }
            type="info"
            showIcon
            style={{ marginBottom: '16px' }}
          />
        )}

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredCertificates}
          rowKey="id"
          pagination={{
            total: filteredCertificates.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 证书详情模态框 */}
      <Modal
        title="证书详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
          <Button key="download" type="primary" icon={<DownloadOutlined />}>
            下载证书
          </Button>,
        ]}
        width={700}
      >
        {selectedCertificate && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="域名" span={2}>
              {selectedCertificate.domain}
            </Descriptions.Item>
            <Descriptions.Item label="CA机构">
              {selectedCertificate.provider}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={getStatusConfig(selectedCertificate.status).color}>
                {getStatusConfig(selectedCertificate.status).text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="签发时间">
              {selectedCertificate.issueDate || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="过期时间">
              {selectedCertificate.expiryDate || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="自动续期">
              <Tag color={selectedCertificate.autoRenew ? 'blue' : 'default'}>
                {selectedCertificate.autoRenew ? '已启用' : '已禁用'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="部署状态">
              <Tag color={getDeployStatusConfig(selectedCertificate.deployStatus).color}>
                {getDeployStatusConfig(selectedCertificate.deployStatus).text}
              </Tag>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default CertificateManage; 